<template>
  <div class="skills-analysis">
    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <template #header>
        <div class="card-header">
          <span>筛选条件</span>
        </div>
      </template>
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="城市">
          <el-select v-model="filterForm.city" placeholder="请选择城市" clearable>
            <el-option label="北京" value="北京" />
            <el-option label="上海" value="上海" />
            <el-option label="广州" value="广州" />
          </el-select>
        </el-form-item>
        <el-form-item label="经验要求">
          <el-select v-model="filterForm.experience" placeholder="请选择经验要求" clearable>
            <el-option label="1-3年" value="1-3年" />
            <el-option label="3-5年" value="3-5年" />
            <el-option label="5-10年" value="5-10年" />
            <el-option label="10年以上" value="10年以上" />
            <el-option label="不限" value="不限" />
          </el-select>
        </el-form-item>
        <el-form-item label="学历要求">
          <el-select v-model="filterForm.education" placeholder="请选择学历要求" clearable>
            <el-option label="大专" value="大专" />
            <el-option label="本科" value="本科" />
            <el-option label="硕士" value="硕士" />
            <el-option label="博士" value="博士" />
            <el-option label="不限" value="不限" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">应用筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 技能分布 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>技能词云</span>
            </div>
          </template>
          <div ref="wordCloudChart" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>技能分布</span>
            </div>
          </template>
          <div ref="skillBarChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

<!--    &lt;!&ndash; 技能组合 &ndash;&gt;-->
<!--    <el-card class="chart-card">-->
<!--      <template #header>-->
<!--        <div class="card-header">-->
<!--          <span>技能组合分析</span>-->
<!--        </div>-->
<!--      </template>-->
<!--      <div ref="combinationChart" class="chart"></div>-->
<!--    </el-card>-->

    <!-- 智能感知 -->
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>智能感知</span>
          <el-button
            type="primary"
            :loading="adviceLoading"
            :disabled="adviceLoading"
            @click="fetchAdvice"
            class="advice-btn"
          >
            <el-icon v-if="!adviceLoading" style="margin-right:4px;"><Lightning /></el-icon>
            {{ adviceLoading ? '生成中...' : '获取智能建议' }}
          </el-button>
          <span v-if="adviceLoading" class="advice-tip">智能建议生成可能需要几秒钟，请耐心等待...</span>
        </div>
      </template>
      <div v-loading="adviceLoading" class="advice-content">
        <div v-for="(point, index) in advicePoints" :key="index" class="advice-point">
          <h3 v-html="point.title"></h3>
          <div v-html="point.content" class="advice-text"></div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import 'echarts-wordcloud'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Lightning } from '@element-plus/icons-vue'

// 筛选表单
const filterForm = ref({
  city: '',
  experience: '',
  education: ''
})

// 图表实例
let wordCloudChartInstance = null
let skillBarChartInstance = null
let combinationChartInstance = null

// 图表DOM引用
const wordCloudChart = ref(null)
const skillBarChart = ref(null)
const combinationChart = ref(null)

// 智能感知相关
const adviceLoading = ref(false)
const advicePoints = ref([])

// 获取技能分布数据
const fetchSkillDistribution = async () => {
  try {
    const params = new URLSearchParams()
    if (filterForm.value.city) {
      params.append('city', filterForm.value.city)
    }
    if (filterForm.value.experience) {
      params.append('experience', filterForm.value.experience)
    }
    if (filterForm.value.education) {
      params.append('education', filterForm.value.education)
    }

    const response = await axios.get(`http://localhost:8081/api/skills/distribution?${params.toString()}`)
    if (response.data.code === 200) {
      initWordCloudChart(response.data.data.list)
      initSkillBarChart(response.data.data.list)
    }
  } catch (error) {
    ElMessage.error('获取技能分布数据失败')
  }
}

// 获取技能组合数据
const fetchSkillCombinations = async () => {
  try {
    const params = new URLSearchParams()
    if (filterForm.value.city) {
      params.append('city', filterForm.value.city)
    }
    if (filterForm.value.experience) {
      params.append('experience', filterForm.value.experience)
    }
    if (filterForm.value.education) {
      params.append('education', filterForm.value.education)
    }

    const response = await axios.get(`http://localhost:8081/api/skills/combinations?${params.toString()}`)
    if (response.data.code === 200) {
      initCombinationChart(response.data.data.list)
    }
  } catch (error) {
    ElMessage.error('获取技能组合数据失败')
  }
}

// 获取智能建议
const fetchAdvice = async () => {
  try {
    adviceLoading.value = true
    const response = await axios.get('http://localhost:8081/api/advice/skill')
    if (response.data.code === 200) {
      advicePoints.value = response.data.data.advicePoints
    }
  } catch (error) {
    ElMessage.error('获取智能建议失败')
  } finally {
    adviceLoading.value = false
  }
}

// 初始化词云图
const initWordCloudChart = (data) => {
  if (!wordCloudChart.value) return

  wordCloudChartInstance = echarts.init(wordCloudChart.value)
  const option = {
    tooltip: {
      show: true,
      formatter: function(params) {
        const item = data.find(d => d.skill === params.name)
        return `${params.name}<br/>占比: ${params.value}%<br/>数量: ${item.count}`
      }
    },
    series: [{
      type: 'wordCloud',
      shape: 'circle',
      left: 'center',
      top: 'center',
      width: '90%',
      height: '90%',
      right: null,
      bottom: null,
      sizeRange: [12, 60],
      rotationRange: [-90, 90],
      rotationStep: 45,
      gridSize: 8,
      drawOutOfBound: false,
      textStyle: {
        fontFamily: 'sans-serif',
        fontWeight: 'bold',
        color: function () {
          return 'rgb(' + [
            Math.round(Math.random() * 160),
            Math.round(Math.random() * 160),
            Math.round(Math.random() * 160)
          ].join(',') + ')'
        }
      },
      emphasis: {
        focus: 'self',
        textStyle: {
          shadowBlur: 10,
          shadowColor: '#333'
        }
      },
      data: data.map(item => ({
        name: item.skill,
        value: item.percentage
      }))
    }]
  }
  wordCloudChartInstance.setOption(option)
}

// 初始化技能分布柱状图
const initSkillBarChart = (data) => {
  if (!skillBarChart.value) return

  skillBarChartInstance = echarts.init(skillBarChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        const item = data.find(d => d.skill === params[0].name)
        return `${params[0].name}<br/>占比: ${params[0].value}%<br/>数量: ${item.count}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '占比 (%)'
    },
    yAxis: {
      type: 'category',
      data: data.map(item => item.skill),
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    series: [
      {
        name: '占比',
        type: 'bar',
        data: data.map(item => item.percentage),
        label: {
          show: true,
          position: 'right',
          formatter: '{c}%'
        }
      }
    ]
  }
  skillBarChartInstance.setOption(option)
}

// 初始化技能组合图
const initCombinationChart = (data) => {
  if (!combinationChart.value) return

  combinationChartInstance = echarts.init(combinationChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        const item = data.find(d => d.combination === params[0].name)
        return `${params[0].name}<br/>占比: ${params[0].value}%<br/>数量: ${item.count}`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '占比 (%)'
    },
    yAxis: {
      type: 'category',
      data: data.map(item => item.combination),
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    series: [
      {
        name: '占比',
        type: 'bar',
        data: data.map(item => item.percentage),
        label: {
          show: true,
          position: 'right',
          formatter: '{c}%'
        }
      }
    ]
  }
  combinationChartInstance.setOption(option)
}

// 处理筛选
const handleFilter = () => {
  fetchSkillDistribution()
  fetchSkillCombinations()
}

// 重置筛选
const resetFilter = () => {
  filterForm.value = {
    city: '',
    experience: '',
    education: ''
  }
  handleFilter()
}

// 处理窗口大小变化
const handleResize = () => {
  wordCloudChartInstance?.resize()
  skillBarChartInstance?.resize()
  combinationChartInstance?.resize()
}

onMounted(() => {
  fetchSkillDistribution()
  fetchSkillCombinations()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  wordCloudChartInstance?.dispose()
  skillBarChartInstance?.dispose()
  combinationChartInstance?.dispose()
})
</script>

<style scoped>
.skills-analysis {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-select) {
  width: 180px;
}

:deep(.el-form-item__content) {
  flex-wrap: wrap;
}

.advice-content {
  padding: 20px;
}

.advice-point {
  margin-bottom: 30px;
}

.advice-point:last-child {
  margin-bottom: 0;
}

.advice-point h3 {
  margin-bottom: 15px;
  color: #409EFF;
}

.advice-text {
  line-height: 1.8;
  color: #606266;
}

.advice-text :deep(p) {
  margin-bottom: 10px;
}

.advice-text :deep(ul) {
  padding-left: 20px;
  margin-bottom: 10px;
}

.advice-text :deep(li) {
  margin-bottom: 5px;
}

.advice-text :deep(strong) {
  color: #303133;
}

.advice-btn {
  border-radius: 24px;
  font-weight: 600;
  background: linear-gradient(90deg, #409EFF 0%, #36D1DC 100%);
  box-shadow: 0 2px 8px rgba(64,158,255,0.08);
  transition: all 0.2s;
  padding: 0 24px;
}
.advice-btn:hover {
  filter: brightness(1.08);
  box-shadow: 0 4px 16px rgba(64,158,255,0.15);
}
.advice-tip {
  margin-left: 16px;
  color: #909399;
  font-size: 14px;
  vertical-align: middle;
}
</style> 